package com.byit.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.byit.builder.MapBuilder;
import com.byit.constant.DefaultValue;
import com.byit.domain.SysMessageNotice;
import com.byit.enums.PromptInfo;
import com.byit.log.ChannelType;
import com.byit.log.Log;
import com.byit.log.OperatorType;
import com.byit.msg.MessageResult;
import com.byit.service.ISysMessageNoticeService;
import com.byit.shrio.session.SessionHelper;
import com.byit.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SysMessageNoticeController
 * @Description TODO
 * @Author lxp
 * @Date 2019-01-24 17:15
 **/
@RestController
@RequestMapping("/api/sys/sysMessageNotice")
public class SysMessageNoticeController {

    @Autowired
    private ISysMessageNoticeService sysMessageNoticeService;


    //页面请求
    @GetMapping("/socket/{cid}")
    public ModelAndView socket(@PathVariable String cid) {
        ModelAndView mav = new ModelAndView("/socket");
        mav.addObject("cid", cid);
        return mav;
    }

  /*  //推送数据接口
    @ResponseBody
    @RequestMapping("/socket/push/{cid}")
    public Object pushToWeb(@PathVariable String cid, String message) {
        try {
            WebSocketServer.sendInfo(message);
        } catch (IOException e) {
            e.printStackTrace();
            return MessageResult.error(cid + "#" + e.getMessage());
        }
        return MessageResult.success(cid);
    }*/


    /**
     * 新增或修改web消息通知信息
     *
     * @param session
     * @return
     */
    @PostMapping("/add")
    @Log(title = "web消息通知", operate = OperatorType.DATA_INSERT, channel = ChannelType.WEB_INTER)
    public Object insertAnnouncement(HttpSession session,
                                     SysMessageNotice sysMessageNotice,
                                     @RequestParam(value = "companyId", defaultValue = "") String companyId,
                                     @RequestParam(value = "userIds", defaultValue = "") String userIds) {
        Long opseruserId = SessionHelper.getUserId(session);
        Long userId = SessionHelper.getUserId(session);
        try {
            if (null == sysMessageNotice) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }
            if (sysMessageNotice.getMsg() == null || sysMessageNotice.getMsg().length() > 100) {
                return MessageResult.warpper("001", null, "内容不超过100字符");
            }
            sysMessageNotice.setOperationId(userId);
            sysMessageNotice.setCreateTime(new Date());
            sysMessageNotice.setUpdateTime(new Date());
            //// 加密用户密码
            sysMessageNotice.setOperationId(opseruserId);
            //某个机构的消息
            if (StringUtils.isNotEmpty(companyId)) {
                sysMessageNotice.setCompanyId(Long.valueOf(companyId));
            }
            //某个用户的消息
            if (StringUtils.isNotEmpty(userIds)) {
                String[] userIdss = userIds.split(",");
                for (int i = 0; i < userIdss.length; i++) {
                    sysMessageNoticeService.insertOrUpdate(sysMessageNotice);
                }
            } else {
                sysMessageNoticeService.insertOrUpdate(sysMessageNotice);
            }
            /**
             * TODO...
             * 给Web发送消息
             */
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }

    /**
     * 新增或修改web消息通知信息
     *
     * @param session
     * @return
     */
    @PostMapping("/edit")
    @Log(title = "web消息通知", operate = OperatorType.DATA_UPDATE, channel = ChannelType.WEB_INTER)
    public Object edit(HttpSession session, SysMessageNotice sysMessageNotice
    ) {

        Long userId = SessionHelper.getUserId(session);
        // String path = appNewsService.getPictrePath(file, "sysMessageNoticeAtachement");
        //   sysMessageNotice.setUrl(url);
        try {
            if (StringUtil.isEmpty(sysMessageNotice.getId())) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }
            if (sysMessageNotice.getMsg() == null || sysMessageNotice.getMsg().length() > 100) {
                return MessageResult.warpper("001", null, "内容不超过100字符");
            }
            sysMessageNotice.setCreateTime(new Date());
            sysMessageNotice.setUpdateTime(new Date());
            //// 加密用户密码
            sysMessageNotice.setOperationId(userId);

            sysMessageNoticeService.insertOrUpdate(sysMessageNotice);
            /**
             * TODO...
             * 给Web发送消息
             */
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }

    /**
     * 通过Id查询web消息通知
     *
     * @param id
     * @return
     */
    @GetMapping("/details")
    @Log(title = "web消息通知", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    public Object selectSysMessageNoticeById(@RequestParam("id") Integer id) {
        SysMessageNotice sysMessageNotice = sysMessageNoticeService.selectById(id);

        return MessageResult.success(sysMessageNotice);
    }

    /**
     * 按照条件查询web消息通知
     *
     * @param session
     * @param title
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    @Log(title = "web消息通知", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    public Object sysMessageNoticeList(HttpSession session,
                                       @RequestParam(value = "title", defaultValue = "") String title,
                                       @RequestParam(value = "page", defaultValue = DefaultValue.PAGE_FIRST) int page,
                                       @RequestParam(value = "limit", defaultValue = DefaultValue.PAGE_SIZE) int limit) {
        Page<SysMessageNotice> pageInfo = new Page<>(page, limit);
        //web消息权限控制
        Long companyId = SessionHelper.getCompanyId(session);
        Long userId = SessionHelper.getUserId(session);
        Map<String, Object> params = MapBuilder.newMap(5)
                .setParam("companyId", companyId)
                .setParam("operationId", userId)
                .ok();
        if (null != title && !"".equals(title)) {
            params.put("title", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(title) + "%");
        }
        Page<JSONObject> result = sysMessageNoticeService.selectSysMessageNoticeAll(pageInfo, params);

        return MessageResult.warpper(PromptInfo.SYS_SECCUSS, result);
    }


    /**
     * 我的web消息通知
     *
     * @param session
     * @param title
     * @return
     */
    @GetMapping("/self")
    @Log(title = "web消息通知", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    public Object getSysMessageOfSelf(HttpSession session,
                                      @RequestParam(value = "title", defaultValue = "") String title
    ) {
        //web消息权限控制
        Long companyId = SessionHelper.getCompanyId(session);
        Long userId = SessionHelper.getUserId(session);
        Map<String, Object> params = MapBuilder.newMap(5)
                .setParam("companyId", companyId)
                .setParam("userId", userId)
                .ok();
        if (null != title && !"".equals(title)) {
            params.put("title", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(title) + "%");
        }
        List<JSONObject> result = sysMessageNoticeService.selectInfoByConmpanyAndUserID(params);

        return MessageResult.warpper(PromptInfo.SYS_SECCUSS, result);
    }

    /**
     * 逻辑删除web消息通知信息
     *
     * @param session
     * @param ids
     * @return
     */
    @PostMapping("/del")
    @Log(title = "web消息通知", operate = OperatorType.DATA_DELETE, channel = ChannelType.WEB_INTER)
    public Object delAppNewsByIds(HttpSession session, @RequestParam("ids") String ids) {
        Long userId = SessionHelper.getUserId(session);
        List<Long> idList = StringUtil.splitLong(ids, ",");
        Map<String, Object> map = MapBuilder.newMap(3).setParam("updateTime", new Date()).setParam("operId", userId).ok();

        for (Long id : idList) {

            map.put("id", id);
            sysMessageNoticeService.delSysMessageNoticeById(map);
        }
        return MessageResult.success();
    }
}
